/*
 * Tao8 project
 * Copyright on iron.yin@gmai.com
 * Create on 2012-4-16
 */
package cc.risingsun.wing.core.util;

import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 加密辅助类
 * 
 * @author iron.yin@gmail.com
 * @sina 1.0
 */
public final class Encrypt {

	private static final Logger logger = LoggerFactory.getLogger(Encrypt.class);

	private static MessageDigest md5;
	private static MessageDigest sha;

	static {
		try {
			md5 = MessageDigest.getInstance("md5");
			sha = MessageDigest.getInstance("sha1");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}

	public static String md5Encrypt(String src) {
		byte[] bytes = md5.digest(src.getBytes());
		md5.reset();
		return bytes2hex(bytes);
	}
	
	public static String shaEncrypt(String src){
		byte[] bytes = sha.digest(src.getBytes());
		sha.reset();
		return bytes2hex(bytes);
	}

	private static String bytes2hex(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		for (byte b : bytes) {
			int r = b & 0xff;
			String hexStr = Integer.toHexString(r);
			if (r <= 0x0f) {
				sb.append(0);
			}
			sb.append(hexStr);
		}
		return sb.toString();
	}
}
